﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PayloadTracker.APRS.SoundModem
{
    public delegate void AX25PacketReadyDelegate(AX25Packet packet);
    public class AX25Deserializer
    {
        enum CONSTS : byte
        {
            SEPARATOR = 0x7E // 0111110
        }
        byte m_BitAcc, m_ByteAcc;
        int m_ByteAccLen;
        int m_TrueBitsInaRow;
        List<Byte> m_BytesToProcess;

        public event AX25PacketReadyDelegate AX25PacketReady;

        public AX25Deserializer()
        {
            m_BytesToProcess = new List<byte>();
            m_BitAcc = m_ByteAcc = 0;
            m_TrueBitsInaRow = m_ByteAccLen = 0;
        }

        private void Reset()
        {
            m_BytesToProcess.Clear();
            m_BitAcc = 0;
            m_ByteAcc = 0;
            m_ByteAccLen = 0;
        }

        public void ProcessBit(bool bit)
        {
            //Logger.LOG.Write(bit ? "1" : "0");

            if (m_TrueBitsInaRow == 5 && !bit)
            {
                //bit packing get out.
                m_TrueBitsInaRow = 0;
                return;
            }
            if (bit)
                m_TrueBitsInaRow++;
            else
                m_TrueBitsInaRow = 0;



            m_BitAcc = ((byte)(((uint)m_BitAcc) << 1));
            if (bit) m_BitAcc |= 1;


            if (m_BitAcc == ((Byte)CONSTS.SEPARATOR))
            {
//                if (b == (Byte)CONSTS.SEPARATOR)
                    Logger.LOG.WriteLine("Got AX.25 FLAG");
                //We have one of of our lovely flag bytes.
                if (m_BytesToProcess.Count > 1)
                {//if we already have a packet going put it through and assemble.
                    ProcessByte(((Byte)CONSTS.SEPARATOR));
                    Reset();
                    ProcessByte(((Byte)CONSTS.SEPARATOR));
                }
                else if (m_BytesToProcess.Count == 1)
                {
                    //We already have just 1 so the one in the queue is now bunk.
                    //get rid of the cue this one.
                    Reset();
                    ProcessByte(((Byte)CONSTS.SEPARATOR));
                }
                else if (m_BytesToProcess.Count == 0)
                {
                    //this is obviously the first one.
                    m_ByteAccLen = 0;
                    ProcessByte(((Byte)CONSTS.SEPARATOR));
                    m_ByteAcc = 0;

                }

            }
            else if (m_BytesToProcess.Count > 0)
                //we have something going so lets keep it up!
                AssembleByte(bit);

        }
        public void AssembleByte(bool bit)
        {
            //Most significant bit first.
            //m_ByteAcc = ((byte)(((uint)m_ByteAcc) << 1));
            //if (bit) m_ByteAcc |= 1;

            //Least significant bit first.
            if (bit) m_ByteAcc = ((byte)(((int)m_ByteAcc) | (1 << m_ByteAccLen)));

            if (++m_ByteAccLen == 8)
            {
                //we have assembled a byte!
                m_ByteAccLen = 0;
                ProcessByte(m_ByteAcc);
                m_ByteAcc = 0;
            }
        }
        private void ProcessByte(Byte b)
        {

            
            //string bitstring = Convert.ToString(b, 2);
            //while (bitstring.Length < 8)
            //    bitstring = "0" + bitstring;
            //Logger.LOG.WriteLine("Byte received: " + bitstring);

            m_BytesToProcess.Add(b);

            if (b == (Byte)CONSTS.SEPARATOR && m_BytesToProcess.Count > 2)
            {
                //add the end byte and assemble it and reset for next frame.
                AssembleFrame();
                Logger.LOG.WriteLine("Finished assembling frame. Resettings.");
            }
        }

        private void AssembleFrame()
        {
            Logger.LOG.WriteLine("Assembling Frame... ");

            try
            {


                //foreach (byte b in m_BytesToProcess)
                //{
                //    string bitstring = Convert.ToString(b, 2);
                //    while (bitstring.Length < 8)
                //        bitstring = "0" + bitstring;

                //    Logger.LOG.WriteLine("Byte: " + bitstring + " H: 0x" + Convert.ToString(b, 16) + " D: " + b.ToString() + " A: " + System.Text.ASCIIEncoding.ASCII.GetString(new byte[] { b }));

                //}

                //do checksum check.
                ushort computedcrc = GenerateCRC_CCITT();


                byte[] bcrc = m_BytesToProcess.GetRange(m_BytesToProcess.Count - 3, 2).ToArray();
                ushort crc = ((ushort)((((uint)bcrc[1]) << 8) | ((uint)bcrc[0])));

                if (computedcrc != crc)
                {
                    Logger.LOG.Error("Invalid AX.25 Packet CRC, discarding... (probably too much noise)");
                    return;
                }



                int o = 1;

                //get the callsigns & ssids.
                string callsign1 = string.Empty;
                for (int i = 1; i <= 6; i++)
                {
                    byte ascii = ((byte)(m_BytesToProcess[i] >> 1));
                    callsign1 += System.Text.ASCIIEncoding.ASCII.GetString(new byte[] { ascii });
                }
                byte callsign1ssid = ((byte)((m_BytesToProcess[7] >> 1) & 0x3F));

                string callsign2 = string.Empty;
                for (int i = 8; i <= 13; i++)
                {
                    byte ascii = ((byte)((m_BytesToProcess[i] >> 1)));
                    callsign2 += System.Text.ASCIIEncoding.ASCII.GetString(new byte[] { ascii });
                }
                byte callsign2ssid = ((byte)((m_BytesToProcess[14] >> 1) & 0x3F));

                //Logger.LOG.WriteLine("Callsign1: " + callsign1 + " (" + callsign1ssid + ")");
                //Logger.LOG.WriteLine("Callsign2: " + callsign2 + " (SSID:" + callsign2ssid + ")");

                o = 13;
                //trim the rest of the address field possibly do something with it?
                while ((m_BytesToProcess[o++] & 1) != 1) ;

                byte control = m_BytesToProcess[o++];

                if ((control & 3) != 3)
                {//we ONLY care about U Frames not S frames or I frames.
                    Logger.LOG.WriteLine("AX.25 Frame with Control of " + Convert.ToString(control, 2) + " received. Ignoring frame! (We wanted 00000011)");
                    return;
                }

                byte pid = m_BytesToProcess[o++];

                byte[] data = m_BytesToProcess.GetRange(o, m_BytesToProcess.Count - 3 - o).ToArray();


                //build and fire event.
                AX25Packet packet = new AX25Packet();
                packet.CallsignFrom = callsign1;
                packet.SSIDFrom = System.Text.ASCIIEncoding.ASCII.GetString(new byte[] { callsign1ssid});
                packet.CallsignTo = callsign2;
                packet.SSIDTo = System.Text.ASCIIEncoding.ASCII.GetString(new byte[] { callsign2ssid });
                packet.PID = pid;
                packet.Control = control;

                packet.Data = data;

                AX25PacketReadyDelegate handler = AX25PacketReady;
                if (handler != null)
                    handler(packet);
            }

            catch (System.Exception e)
            {
                Logger.LOG.Error("Failed to deserialize AX.25 frame due to: " + e.ToString());
                Reset();
            }
        }

        private ushort GenerateCRC_CCITT()
        {
            ushort computedcrc = 0xffff;
            for (int i = 1; i < m_BytesToProcess.Count - 3; i++)
            {
                byte c = m_BytesToProcess[i];
                for (byte bit = 8; bit != 0; bit--)
                {
                    if (((computedcrc ^ c) & 1) != 0)
                        computedcrc = ((ushort)((computedcrc >> 1) ^ 0x8408));
                    else
                        computedcrc = ((ushort)(computedcrc >> 1));
                    c = ((byte)(c >> 1));
                }
            }
            computedcrc = ((ushort)~computedcrc);
            return computedcrc;
        }
    }
}
